/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ProductInputPane.java
 *
 * Created on 24-jul-2010, 17:29:10
 */

package facturasapp;

import facturasapp.data.StoreManager;
import facturasapp.events.FacturaEvent;
import facturasapp.events.EventManager;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;
import storeDataModel.Product;
import storeDataModel.ProductRelation;

/**
 *
 * @author CiberXtrem
 */
public class ProductInputPane extends javax.swing.JPanel {

    /** Creates new form ProductInputPane */
    public ProductInputPane() {
        initComponents();
        //initCustomComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        codigoLabel = new javax.swing.JLabel();
        codigoField = new javax.swing.JTextField();
        descripcionLabel = new javax.swing.JLabel();
        descripcionField = new javax.swing.JTextField();
        precioLabel = new javax.swing.JLabel();
        precioField = new javax.swing.JTextField();
        cantidadLabel = new javax.swing.JLabel();
        cantidadField = new javax.swing.JTextField();
        importeLabel = new javax.swing.JLabel();
        importeField = new javax.swing.JTextField();
        addProductoCestaButton = new javax.swing.JButton();

        setName("Form"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(facturasapp.FacturasApp.class).getContext().getResourceMap(ProductInputPane.class);
        codigoLabel.setFont(resourceMap.getFont("codigoLabel.font")); // NOI18N
        codigoLabel.setText(resourceMap.getString("codigoLabel.text")); // NOI18N
        codigoLabel.setName("codigoLabel"); // NOI18N

        codigoField.setText(resourceMap.getString("codigoField.text")); // NOI18N
        codigoField.setName("codigoField"); // NOI18N
        codigoField.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                codigoFieldFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                codigoFieldFocusLost(evt);
            }
        });

        descripcionLabel.setFont(resourceMap.getFont("descripcionLabel.font")); // NOI18N
        descripcionLabel.setText(resourceMap.getString("descripcionLabel.text")); // NOI18N
        descripcionLabel.setName("descripcionLabel"); // NOI18N

        descripcionField.setText(resourceMap.getString("descripcionField.text")); // NOI18N
        descripcionField.setName("descripcionField"); // NOI18N
        descripcionField.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                descripcionFieldFocusGained(evt);
            }
        });

        precioLabel.setFont(resourceMap.getFont("precioLabel.font")); // NOI18N
        precioLabel.setText(resourceMap.getString("precioLabel.text")); // NOI18N
        precioLabel.setName("precioLabel"); // NOI18N

        precioField.setText(resourceMap.getString("precioField.text")); // NOI18N
        precioField.setName("precioField"); // NOI18N
        precioField.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                precioFieldFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                precioFieldFocusLost(evt);
            }
        });

        cantidadLabel.setFont(resourceMap.getFont("cantidadLabel.font")); // NOI18N
        cantidadLabel.setText(resourceMap.getString("cantidadLabel.text")); // NOI18N
        cantidadLabel.setName("cantidadLabel"); // NOI18N

        cantidadField.setText(resourceMap.getString("cantidadField.text")); // NOI18N
        cantidadField.setName("cantidadField"); // NOI18N
        cantidadField.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                cantidadFieldFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                cantidadFieldFocusLost(evt);
            }
        });

        importeLabel.setFont(resourceMap.getFont("importeLabel.font")); // NOI18N
        importeLabel.setText(resourceMap.getString("importeLabel.text")); // NOI18N
        importeLabel.setName("importeLabel"); // NOI18N

        importeField.setText(resourceMap.getString("importeField.text")); // NOI18N
        importeField.setName("importeField"); // NOI18N

        addProductoCestaButton.setIcon(resourceMap.getIcon("addProductoCestaButton.icon")); // NOI18N
        addProductoCestaButton.setText(resourceMap.getString("addProductoCestaButton.text")); // NOI18N
        addProductoCestaButton.setName("addProductoCestaButton"); // NOI18N
        addProductoCestaButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addProductoCestaButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(codigoField, javax.swing.GroupLayout.PREFERRED_SIZE, 61, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(codigoLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(descripcionLabel)
                    .addComponent(descripcionField, javax.swing.GroupLayout.PREFERRED_SIZE, 225, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(precioLabel)
                    .addComponent(precioField, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(cantidadField, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cantidadLabel))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(importeLabel)
                    .addComponent(importeField, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(addProductoCestaButton, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(addProductoCestaButton)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(importeLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 25, Short.MAX_VALUE)
                            .addComponent(cantidadLabel))
                        .addGap(20, 20, 20))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(3, 3, 3)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(codigoLabel)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(codigoField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(descripcionLabel)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(descripcionField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(precioLabel)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(precioField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(cantidadField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(importeField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))))
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

   // public void initCustomComponentes(){
        
    //}

    public void updateImporte(){
        float precio = Float.parseFloat(precioField.getText());
        int cantidad = Integer.parseInt(cantidadField.getText());
        float importe = precio * (float) cantidad;

        importeField.setText(String.valueOf(importe));
    }

    public void resetValues(){
        codigoField.setText("");
        descripcionField.setText("");
        precioField.setText("0.00");
        cantidadField.setText("1");
        importeField.setText("0.00");
    }

    private void addProductoCestaButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addProductoCestaButtonActionPerformed

        Product product = new Product(codigoField.getText());

        try{
        PersistenceManagerFactory pmf = StoreManager.get();
        PersistenceManager pm = pmf.getPersistenceManager();
        pm.currentTransaction().begin();

        //Obtener el producto de la base de datos y si no existe...
        Query query = pm.newQuery(Product.class, "codigo == p_codigo");
        query.declareParameters("String p_codigo");
        query.setUnique(true);
        Product aProduct = (Product)query.execute(codigoField.getText());

        if(aProduct!= null){
            //Detach Copy of Product: Puede ser modificada fuera de una transaccion y al almacenar de nuevo
            //se updatea en base de datos
            product = pm.detachCopy(aProduct);
        }
        else{
            product = new Product(codigoField.getText());
        }

        //End Crear Producto si no existe en base de datos
        pm.currentTransaction().commit();
        pm.close();
        ///End obtener producto de base de datos
        }
        catch(Exception e){
            
        }
        
        String codigo = codigoField.getText();
        product.setCodigo(codigo);

        String descripcion = descripcionField.getText();
        product.setDescripcion(descripcion);

        float precio = Float.parseFloat(precioField.getText());
        product.setPrecio(precio);

        //Creamos el ProductRelation
        int cantidad = Integer.parseInt(cantidadField.getText());
        float importe = Float.parseFloat(importeField.getText());
        ProductRelation productRelation = new ProductRelation(product, cantidad, importe);

        //Creamos el Facturevent
        FacturaEvent event = new FacturaEvent(productRelation);

        //Enviamos el evento de nuevo producto con el productRelation como source
        EventManager.getInstance().fireFacturaEvent(event, EventManager.INVOICE_PRODUCT_ADDED);

        //Reseteamos los valores visuales
        resetValues();
    }//GEN-LAST:event_addProductoCestaButtonActionPerformed

    private void codigoFieldFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_codigoFieldFocusLost
        
        codigoField.setText(codigoField.getText().toUpperCase());
        // Buscamos en la base de datos a ver si existe el producto con el codigo indicado
        PersistenceManagerFactory pmf = StoreManager.get();
        PersistenceManager pm = pmf.getPersistenceManager();
        pm.currentTransaction().begin();

        //Obtener el producto de la base de datos y si no existe...
        Query query = pm.newQuery(Product.class, "codigo == p_codigo");
        query.declareParameters("String p_codigo");
        query.setUnique(true);
        Product aProduct = (Product)query.execute(codigoField.getText());

        //Actualizamos todos los campos con los valores del producto en base de datos
        if(aProduct!=null){
            precioField.setText(String.valueOf(aProduct.getPrecio()));
            descripcionField.setText(aProduct.getDescripcion());
        }

        updateImporte();
        
        pm.currentTransaction().commit();
        pm.close();

    }//GEN-LAST:event_codigoFieldFocusLost

    private void precioFieldFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_precioFieldFocusLost
        //Al especificar el precio automaticamente setteamos el importe al valor = precio * cantidad
        String precio_str = precioField.getText();
        precio_str = precio_str.equals("") ? "0.0" : precio_str;
        precioField.setText(precio_str);
        updateImporte();
    }//GEN-LAST:event_precioFieldFocusLost

    private void cantidadFieldFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_cantidadFieldFocusLost
        String cantidad_str = cantidadField.getText();
        cantidad_str = cantidad_str.equals("") ? "1" : cantidad_str;
        cantidadField.setText(cantidad_str);
        updateImporte();
    }//GEN-LAST:event_cantidadFieldFocusLost

    private void precioFieldFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_precioFieldFocusGained
        precioField.selectAll();
    }//GEN-LAST:event_precioFieldFocusGained

    private void codigoFieldFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_codigoFieldFocusGained
        codigoField.selectAll();
    }//GEN-LAST:event_codigoFieldFocusGained

    private void descripcionFieldFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_descripcionFieldFocusGained
        descripcionField.selectAll();
    }//GEN-LAST:event_descripcionFieldFocusGained

    private void cantidadFieldFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_cantidadFieldFocusGained
        cantidadField.selectAll();
    }//GEN-LAST:event_cantidadFieldFocusGained


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addProductoCestaButton;
    private javax.swing.JTextField cantidadField;
    private javax.swing.JLabel cantidadLabel;
    private javax.swing.JTextField codigoField;
    private javax.swing.JLabel codigoLabel;
    private javax.swing.JTextField descripcionField;
    private javax.swing.JLabel descripcionLabel;
    private javax.swing.JTextField importeField;
    private javax.swing.JLabel importeLabel;
    private javax.swing.JTextField precioField;
    private javax.swing.JLabel precioLabel;
    // End of variables declaration//GEN-END:variables

    //Custom Data Variables
    
    //End Custom Data Variables
}
